# dota-python 文档网址 https://dota2.readthedocs.io https://steam.readthedocs.io/。该脚本需要翻墙

import configparser
import logging
import threading
import time

import dota2.utils
import pymysql
import steam.enums.emsg
from dota2.client import Dota2Client
from dota2.common_enums import ESOType
from dota2.features import sharedobjects as so
from steam.client import SteamClient

logging.basicConfig(format='[%(asctime)s] %(levelname)s %(name)s: %(message)s', level=logging.DEBUG)

config = configparser.ConfigParser()
config.read("./conf.ini", encoding="utf-8")  # 读取配置文件，如果配置文件不存在则创建

client = SteamClient()

dota = Dota2Client(client)

CSODOTALobbyProto = so.find_so_proto(ESOType.CSODOTALobby)
LobbyState = CSODOTALobbyProto.State


@client.on(client.friends.EVENT_FRIEND_INVITE)
def friend_invite(friend):
    client.friends.add(friend.steam_id)


# @client.on(client.EVENT_DISCONNECTED)
def relogin():
    login()


@dota.on(dota.EVENT_PARTY_INVITE)
def party_invite(party):
    dota.respond_to_party_invite(party_id=party.group_id, accept=True)


@dota.on(dota.EVENT_LOBBY_INVITE)
def lobby_invite(lobby):
    dota.respond_to_lobby_invite(lobby_id=lobby.group_id, accept=True)


@dota.on(dota.EVENT_LOBBY_CHANGED)
def lobby_changed(message):
    if message.HasField('state') and message.state == LobbyState.POSTGAME:
        dota.leave_practice_lobby()
        replay_url = get_replay_url(message.match_id)
        write_match_replay_url_to_mysql(message.match_id, replay_url)


def write_match_replay_url_to_mysql(match_id, replay_url):
    mysql = config['mysql']
    db = pymysql.connect(host=mysql['host'], user=mysql['username'], password=mysql['password'],
                         port=mysql.getint('port'), database=mysql['database'])
    cursor = db.cursor()
    cursor.execute("SELECT count(*) from replay where match_id = %s", match_id)
    data = cursor.fetchone()
    if data[0] == 0:
        cursor.execute('insert into replay (match_id, replay_url) value (%s, %s)', (match_id, replay_url))
    else:
        cursor.execute('update replay set replay_url = %s where match_id = %s', (replay_url, match_id))
    db.commit()
    db.close()


@client.on('logged_on')
def logged_on():
    # client.friends.on(client.friends.EVENT_FRIEND_INVITE, friend_invite)
    dota.launch()


@dota.on('ready')
def do_dota_stuff():
    # dota.on(dota.EVENT_LOBBY_INVITE, lobby_invite)
    # dota.on(dota.EVENT_PARTY_INVITE, party_invite)
    thread = threading.Thread(target=get_old_match_replay_url)
    thread.daemon = True
    thread.start()
    pass


def get_old_match_replay_url():
    mysql = config['mysql']
    while dota.ready or True:
        db = None
        try:
            db = pymysql.connect(host=mysql['host'], user=mysql['username'], password=mysql['password'],
                                 port=mysql.getint('port'), database=mysql['database'])
            cursor = db.cursor()
            cursor.execute("SELECT * from replay where replay_url = '' or replay_url is null")
            data = cursor.fetchall()
            print(data)
            for row in data:
                replay_url = get_replay_url(row[1])
                if replay_url != '' and replay_url is not None:
                    write_match_replay_url_to_mysql(row[1], replay_url)
        except Exception as e:
            logging.error('获取老数据replay_url失败', e)
        if db is not None:
            db.close()
        time.sleep(60 * 10)


def get_replay_url(match_id):
    job_id = dota.request_match_details(match_id)
    details = dota.wait_msg(job_id)
    replay_url = dota2.utils.replay_url(match_id, details.match.cluster, details.match.replay_salt)
    return replay_url


def login():
    client.cm_servers.merge_list([{'162.254.196.83', 27018}])
    client.set_credential_location('./sentry')
    if client.relogin_available:
        client.relogin()
    else:
        steam_config = config['steam']
        client.cli_login(steam_config['username'], steam_config['password'])
    try:
        client.run_forever()
    except KeyboardInterrupt:
        client.logout()
        time.sleep(10)


if __name__ == '__main__':
    login()
    pass
